Micron Document




Java ConcurrentMap
part 6/19 · 30.6 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
One solution to the concurrent modification problem is using a particular wrapper class provided by a factory in java.util.Collections : public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) which wraps an existing non-thread-safe Map with methods that synchronize on an internal mutex.cite-ref-footnotegoetzpeierlsblochbowbeer200684-85-5-2-1-concurrenthashmap-4-0[4] There are also wrappers for the other kinds of Collections. This is a partial solution, because it is still possible that the underlying Map can be inadvertently accessed by Threads which keep or obtain unwrapped references. Also, all Collections implement the java.lang.Iterable but the synchronized-wrapped Maps and other wrapped Collections do not provide synchronized iterators, so the synchronization is left to the client code, which is slow and error prone and not possible to expect to be duplicated by other consumers of the synchronized Map. The entire duration of the iteration must be protected as well. Furthermore, a Map which is wrapped twice in different places will have different internal mutex Objects on which the synchronizations operate, allowing overlap. The delegation is a performance reducer, but modern Just-in-Time compilers often inline heavily, limiting the performance reduction. Here is how the wrapping works inside the wrapper - the mutex is just a final Object and m is the final wrapped Map:

public V put(K key, V value) {
synchronized (mutex) {
return m.put(key, value);
}
}

──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────